package com.wing.product.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.bill.model.entity.BillDetailInfo;
import com.wing.bill.model.entity.WarehouseBill;
import com.wing.bill.service.WarehouseBillDetailService;
import com.wing.bill.service.WarehouseBillService;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.common.utils.UniqueIdGeneratorUtil;
import com.wing.product.dao.WarehouseProductInventoryDao;
import com.wing.product.dao.WarehouseShipmentOrderDao;
import com.wing.product.dao.WarehouseSignOrderDao;
import com.wing.product.model.entity.*;
import com.wing.product.model.request.WarehouseSignInventoryForm;
import com.wing.product.model.request.WarehouseSignOrderDetailForm;
import com.wing.product.model.request.WarehouseSignOrderForm;
import com.wing.product.model.response.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class WarehouseSignOrderServiceImpl extends ServiceImpl<WarehouseSignOrderDao, WarehouseSignOrder> implements WarehouseSignOrderService{


    @Autowired
    private WarehouseSignOrderDetailService warehouseSignOrderDetailService;



    @Autowired
    private WarehouseProductInventoryService warehouseProductInventoryService;


    @Autowired
    private WarehouseOrderService warehouseOrderService;

    @Autowired
    private WarehouseBillDetailService  warehouseBillDetailService;

    @Autowired
    private WarehouseBillService warehouseBillService;
    @Autowired
    private WarehouseShipmentOrderDao warehouseShipmentOrderDao;

    @Autowired
    private WarehouseShipmentOrderService warehouseShipmentOrderService;

    @Autowired
    private WarehouseSignOrderDao warehouseSignOrderDao;

    @Autowired
    private WarehouseProductInventoryDao warehouseProductInventoryDao;



    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean save(WarehouseSignOrderForm warehouseSignOrderForm) {
        // 先判断 是否已经进行了签收
//        warehouseSignOrderForm.getWarehouseSignInventory().stream().map(WarehouseSignInventoryForm::getId).forEach(id -> {
//            WarehouseProductInventory warehouseProductInventory = warehouseProductInventoryService.getById(id);
//            if (ObjectUtil.isNotEmpty(warehouseProductInventory) && warehouseProductInventory.getWarehouseSignOrderId()!=null) {
//                throw new RuntimeException(warehouseProductInventory.getSysBundleCode()+"该商品已经签收");
//            }
//        });
        WarehouseSignOrder warehouseSignOrder = new WarehouseSignOrder();
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(WarehouseSignOrder.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(warehouseSignOrderForm, warehouseSignOrder,copyOptions);
        warehouseSignOrder.setSignCode(UniqueIdGeneratorUtil.generateUniqueId("QR", "yyyyMMddHHmmss", 1000, 9999));
        warehouseSignOrder.setShipmentOrderId(warehouseSignOrderForm.getShipmentOrderId());
        warehouseSignOrder.setTotalQuantity(warehouseSignOrderForm.getTotalQuantity());
        warehouseSignOrder.setStoreTime(LocalDateTime.now());
//        warehouseSignOrder.setTotalQuantity(warehouseSignOrderForm.getTotalQuantity());
        warehouseSignOrder.setStatus(4);
        baseMapper.insert(warehouseSignOrder);


        List<WarehouseProductInventory> warehouseProductInventoryList= new ArrayList<WarehouseProductInventory>();
        for (WarehouseSignInventoryForm warehouseSignInventoryForm : warehouseSignOrderForm.getWarehouseSignInventory()) {
                WarehouseProductInventory warehouseProductInventory =warehouseProductInventoryDao.findByInventoryId(warehouseSignInventoryForm.getId());
                warehouseProductInventory.setSignQualified(warehouseSignInventoryForm.getSignQualified());
                warehouseProductInventory.setRemarks(warehouseSignInventoryForm.getRemarks());
                warehouseProductInventory.setWarehouseSignOrderId(warehouseSignOrder.getId());
                warehouseProductInventory.setIsSign(warehouseSignInventoryForm.getIsSign());
                warehouseProductInventory.setWarehouseId(Long.parseLong(warehouseSignInventoryForm.getWarehouseId()));
            warehouseProductInventory.setUnqualifiedId(warehouseSignInventoryForm.getUnqualifiedId());
            warehouseProductInventory.setUnqualifiedReason(warehouseSignInventoryForm.getUnqualifiedReason());
                if(!StringUtils.isEmpty(warehouseSignInventoryForm.getWarehouseAreaId())){
                    warehouseProductInventory.setWarehouseAreaId(Long.parseLong(warehouseSignInventoryForm.getWarehouseAreaId()));
                }
                if(!StringUtils.isEmpty(warehouseSignInventoryForm.getWarehouseShelfSpaceId())){
                    warehouseProductInventory.setWarehouseShelfSpaceId(Long.parseLong(warehouseSignInventoryForm.getWarehouseShelfSpaceId()));
                }

            warehouseProductInventoryService.updateById(warehouseProductInventory);
//            warehouseProductInventoryDao.insert(warehouseProductInventory);
            warehouseProductInventoryList.add(warehouseProductInventory);
        }

        warehouseShipmentOrderService.updateStatus(warehouseSignOrderForm.getShipmentOrderId(),2);

        //修改发货订单的状态为已签收
        //TODO判断所有的捆包都签收了才能修改

//        List<WarehouseProductInventoryVO> warehouseProductInventoryVOList=warehouseShipmentOrderDao.checkIsSign(warehouseSignOrderForm.getShipmentOrderId());
//        if(warehouseProductInventoryVOList.size()<1){
//            warehouseShipmentOrderService.updateStatus(warehouseSignOrderForm.getShipmentOrderId(),2);
//        }
//        List<WarehouseSignOrderDetail> warehouseSignOrderDetailList = new ArrayList<>();
//        for ( WarehouseSignOrderDetailForm orderDetailForm : warehouseSignOrderForm.getWarehouseSignOrderDetail()) {
//            WarehouseSignOrderDetail warehouseSignOrderDetail = new WarehouseSignOrderDetail();
//            CopyOptions copyDetailOptions = CopyOptions.create()
//                    .setEditable(WarehouseSignOrderDetail.class)
//                    .setIgnoreError(true)
//                    .setIgnoreNullValue(true);
//            BeanUtil.copyProperties(orderDetailForm, warehouseSignOrderDetail, copyDetailOptions);
//            warehouseSignOrderDetail.setSignOrderId(warehouseSignOrder.getId());
//            warehouseSignOrderDetail.setSignOrderCode(warehouseSignOrder.getSignCode());
//            warehouseSignOrderDetail.setShipmentOrderId(warehouseSignOrder.getShipmentOrderId());
//            warehouseSignOrderDetail.setShipmentOrderCode(warehouseSignOrder.getShipmentOrderCode());
//            warehouseSignOrderDetail.setShipmentOrderDetailId(orderDetailForm.getId());
//            warehouseSignOrderDetailList.add(warehouseSignOrderDetail);
//        }
//        warehouseSignOrderDetailService.saveBatch(warehouseSignOrderDetailList);
//        List<WarehouseProductInventory> warehouseProductInventoryList = getWarehouseProductInventories(warehouseSignOrderForm, warehouseSignOrderDetailList);
//        warehouseProductInventoryService.updateBatchById(warehouseProductInventoryList);
        //修改库存相关完成，需要 创建账单记录
//        WarehouseBill warehouseBill = warehouseBillService.isExistBill(warehouseSignOrder.getCustomerId());
////         先判断 头部账单是否存在
//        if(ObjectUtil.isEmpty(warehouseBill)){
////            如果不存在 新增头部订单
//            warehouseBill = warehouseBillService.createBill(warehouseSignOrder.getCustomerId());
//        }
////        生成新的账单
//        return warehouseBillDetailService.addBillDetail(warehouseSignOrder.getCustomerId(), warehouseProductInventoryList.stream().map(
//                product -> {
//                    BillDetailInfo detailInfo = new BillDetailInfo();
//                    detailInfo.setSysBundleCode(product.getSysBundleCode());
//                    detailInfo.setPrice(product.getPrice());
//                    detailInfo.setTransferType(1);
//                    detailInfo.setInventoryId(product.getId());
//                    return detailInfo;
//                }
//        ).collect(Collectors.toList()
//        ),warehouseBill.getId());
        return true;
    }

    @Override
    public Page<WarehouseSignOrderVO> pageList4app(Page page, Map<String, Object> params) {
//        return new PageResult<>(baseMapper.list4app(pg, paramMap));
        List<WarehouseSignOrderVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;

    }


    private static List<WarehouseProductInventory> getWarehouseProductInventories(WarehouseSignOrderForm warehouseSignOrderForm, List<WarehouseSignOrderDetail> warehouseSignOrderDetailList) {
        List<WarehouseProductInventory> warehouseProductInventoryList = new ArrayList<>();
        List<WarehouseSignInventoryForm> warehouseSignInventoryList = warehouseSignOrderForm.getWarehouseSignInventory();
        warehouseSignInventoryList.forEach(warehouseSignInventoryForm -> {
            WarehouseProductInventory warehouseProductInventory = new WarehouseProductInventory();
            CopyOptions copyDetailOptions = CopyOptions.create()
                    .setEditable(WarehouseProductInventory.class)
                    .setIgnoreError(true)
                    .setIgnoreNullValue(true);
            BeanUtil.copyProperties(warehouseSignInventoryForm, warehouseProductInventory, copyDetailOptions);
            warehouseProductInventory.setProductStatus(2);
            // warehouseSignOrderDetailList的.ShipmentOrderId 找到 对应的 signOrderDetailId
            WarehouseSignOrderDetail v =  warehouseSignOrderDetailList.stream()
                    .filter(warehouseSignOrderDetail -> warehouseSignOrderDetail.getShipmentOrderDetailId().equals(warehouseSignInventoryForm.getWarehouseShipmentOrderDetailId())).findFirst().get();
            warehouseProductInventory.setWarehouseSignOrderDetailId(v.getId());
            warehouseProductInventory.setWarehouseSignOrderId(v.getSignOrderId());
            warehouseProductInventory.setId(warehouseSignInventoryForm.getId());
            warehouseProductInventory.setCustomerId(warehouseSignOrderForm.getCustomerId());
            warehouseProductInventory.setIsSign(1);
            warehouseProductInventoryList.add(warehouseProductInventory);
        });
        return warehouseProductInventoryList;
    }

    @Override
    public JsonResult<Map<String,Object>> selectLogistics(){

        Map<String,Object> signMap = new HashMap<>();
        List<WarehouseSignOrderVO> warehouseSignOrderVOS = this.baseMapper.selectLogistics();
        Integer sumSignOrder = 0;
        List<Long> shipmentList = new ArrayList<>();
        for (WarehouseSignOrderVO ws : warehouseSignOrderVOS){
            boolean bl = ws.getCreateTime().toLocalDate().equals(LocalDateTime.now().toLocalDate());
            if (bl){
                sumSignOrder++;
                shipmentList.add(ws.getShipmentOrderId());
            }
        }
        signMap.put("sumSignOrder",sumSignOrder);
        if (CollectionUtils.isNotEmpty(shipmentList)){
            LambdaQueryWrapper<WarehouseShipmentOrder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(WarehouseShipmentOrder::getIsDeleted,0)
                    .in(WarehouseShipmentOrder::getId,shipmentList);
            List<WarehouseShipmentOrder> warehouseShipmentOrders = warehouseShipmentOrderDao.selectList(lambdaQueryWrapper);
            signMap.put("shipmentOrde",warehouseShipmentOrders.size());
        }else {
            signMap.put("shipmentOrde",0);
        }
        signMap.put("warehouseSignOrderVOS",warehouseSignOrderVOS);
        return JsonResult.success(signMap);
    }

    @Override
    public WarehouseShipmentOrderInfoVO info(Long id) {
        WarehouseShipmentOrderInfoVO warehouseShipmentOrderInfoVO=warehouseSignOrderDao.infoIsSign(id);
        warehouseShipmentOrderInfoVO.setOrderInfoDetail(warehouseSignOrderDao.infoDetailIsSign(warehouseShipmentOrderInfoVO.getId()));
        return warehouseShipmentOrderInfoVO;
    }

    @Override
    public WarehouseShipmentOrderInfoVO addInfo(String waybill) {
        WarehouseShipmentOrderInfoVO warehouseShipmentOrderInfoVO=warehouseSignOrderDao.info(waybill);
        warehouseShipmentOrderInfoVO.setOrderInfoDetail(warehouseSignOrderDao.infoDetail(warehouseShipmentOrderInfoVO.getId()));
        return warehouseShipmentOrderInfoVO;
    }

    @Override
    public Boolean signSingle(Long id ,String remarks, Long signQualified,Long areaId,Long spaceId,Long unqualifiedId,String unqualifiedReason) {
        WarehouseProductInventory warehouseProductInventory = warehouseProductInventoryDao.findByInventoryId(id);
        warehouseProductInventory.setIsSign(1);
        warehouseProductInventory.setRemarks(remarks);
        warehouseProductInventory.setSignQualified(signQualified);
        warehouseProductInventory.setWarehouseAreaId(areaId);
        warehouseProductInventory.setWarehouseShelfSpaceId(spaceId);
        warehouseProductInventory.setUnqualifiedId(unqualifiedId);
        warehouseProductInventory.setUnqualifiedReason(unqualifiedReason);
        warehouseProductInventoryDao.updateById(warehouseProductInventory);

        WarehouseSignOrder warehouseSignOrder=baseMapper.selectById(warehouseProductInventory.getWarehouseSignOrderId());
        warehouseSignOrder.setUpdateTime(LocalDateTime.now());
        baseMapper.updateById(warehouseSignOrder);
        return true;
    }

    @Override
    public Boolean updateStatus(Long id, Integer status) {
        WarehouseSignOrder warehouseSignOrder =baseMapper.selectById(id);
        warehouseSignOrder.setStatus(status);
        return true;
    }

    @Override
    public Page<WarehouseSignOrderVO> List4app(Page page, Map<String, Object> params) {
        List<WarehouseSignOrderVO> list = baseMapper.signDetail(page, params);
        page.setRecords(list);
        return page;
    }
}
